package com.quanyan.user.web;

import com.quanyan.api.APIResponse;
import com.quanyan.common.user.AppUserCacheInfo;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.model.vo.request.ReqCommentQuery;
import com.quanyan.user.model.vo.request.ReqDynamic;
import com.quanyan.user.model.vo.request.ReqHomePage;
import com.quanyan.user.model.vo.request.ReqNewsComment;
import com.quanyan.user.model.vo.response.RespHomePage;
import com.quanyan.user.response.ReqReleaseDynamic;
import com.quanyan.user.service.HomePageService;
import com.quanyan.user.service.NewsCommentService;
import com.quanyan.user.service.TopicService;
import com.quanyan.user.service.UserDynamicService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

/**
 * Created by zhang on 16/11/8.
 * 动态
 */
@RestController
@RequestMapping("/api/user/dynamic")
public class UserDynamicController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(UserDynamicController.class);

    @Autowired
    private UserDynamicService userDynamicService;

    @Autowired
    private NewsCommentService newsCommentService;

    @Autowired
    private TopicService topicService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HomePageService homePageService;

    //动态列表
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public APIResponse dynamicList(@RequestBody @Valid ReqDynamic reqDynamic, HttpServletRequest request) {
        try {
            String userCookiesName = request.getHeader("userCookiesName");
            RedisKey redisKey = new RedisKey(userCookiesName, "");
            AppUserCacheInfo appUserCacheInfo = (AppUserCacheInfo) redisTemplate.getObjectFromC(redisKey, AppUserCacheInfo.class);
            if (UserConstants.DynamicType.loadNewsMyAttention == reqDynamic.getType().intValue()
                    || UserConstants.DynamicType.loadNewsMyFans == reqDynamic.getType().intValue()
                    || UserConstants.DynamicType.loadNewsMyDy == reqDynamic.getType().intValue()
                    || UserConstants.DynamicType.loadNewsMyAttentionDaren == reqDynamic.getType().intValue()) {
                if (appUserCacheInfo == null)
                    return APIResponse.returnFail("请先登录!");
            }
            if (appUserCacheInfo != null)
                reqDynamic.setUid(appUserCacheInfo.getUser_id());
            return userDynamicService.queryDynamic(reqDynamic);
        } catch (Exception e) {
            logger.error("{}", e);
            return APIResponse.returnFail("服务器异常！");
        }
    }


    /**
     * 发布动态
     *
     * @param reqReleaseDynamic
     * @param request
     * @return
     */
    @RequestMapping(value = "/releaseDynamic", method = RequestMethod.POST, produces = "application/json")
    public APIResponse addDynamicDetail(@RequestBody @Valid ReqReleaseDynamic reqReleaseDynamic, HttpServletRequest request) {
        try {
            Integer uid = (Integer) request.getAttribute("uid");
            reqReleaseDynamic.setUid(uid);
            return userDynamicService.addDynamicDetail(reqReleaseDynamic);
        } catch (Exception e) {
            logger.error("发布动态失败；{}", e);
            return APIResponse.returnFail("发布动态失败");
        }
    }


    //动态评论列表
    @RequestMapping(value = "/loadComment", method = RequestMethod.POST, produces = "application/json")
    public APIResponse dynamicDetailCommentList(@RequestBody @Valid ReqNewsComment reqNewsComment) {
        return newsCommentService.queryComment(reqNewsComment);
    }


    /**
     * 删除动态
     *
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/deleteDynamic", method = RequestMethod.POST, produces = "application/json")
    public APIResponse deleteDynamicDetail(@RequestBody Map map, HttpServletRequest request) {

        Object obj = map.get("dynamicDetailsId");
        if (obj == null) {
            return APIResponse.returnFail("请传入有效参数！");
        }
        Integer dynamicDetailsId = Integer.parseInt(obj.toString());
        try {
            Integer uid = (Integer) request.getAttribute("uid");
            return userDynamicService.deleteDynamicDetail(uid, dynamicDetailsId);
        } catch (Exception e) {
            logger.error("删除动态失败；{}", e);
            return APIResponse.returnFail("删除动态失败");
        }
    }


    //举报
    @RequestMapping(value = "/report", method = RequestMethod.POST, produces = "application/json")
    public APIResponse reportDynamic(@RequestBody Map map, HttpServletRequest request) {
        try {
            int uid = (int) request.getAttribute("uid");
            Object obj = map.get("dynamicDetailsId");
            if (obj == null) {
                return APIResponse.returnFail("请传入有效参数！");
            }
            Integer dynamicDetailsId = Integer.parseInt(obj.toString());
            return userDynamicService.reportDynamic(uid, dynamicDetailsId);
        } catch (Exception e) {
            logger.error("{}", e);
            return APIResponse.returnFail("服务器异常！");
        }
    }


    //动态详情
    @RequestMapping(value = "/dynamicDetail", method = RequestMethod.POST, produces = "application/json")
    public APIResponse dynamicDetail(@RequestBody Map map, HttpServletRequest request) {
        try {
            Integer uid = this.getUidByUserCookiesName(request);
            Object obj = map.get("dynamicDetailsId");
            if (obj == null) {
                return APIResponse.returnFail("请传入有效参数！");
            }
            Integer dynamicDetailsId = Integer.parseInt(obj.toString());
            return userDynamicService.dynamicDetail(uid, dynamicDetailsId);
        } catch (Exception e) {
            logger.error("{}", e);
            return APIResponse.returnFail("服务器异常！");
        }
    }


    /**
     * 获取首页精选动态列表
     *
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/getFirstNewsList", method = RequestMethod.POST, produces = "application/json")
    public APIResponse getFirstNewsList(@RequestBody Map<String, Integer> map, HttpServletRequest request) {
        String userCookiesName = request.getHeader("userCookiesName");

        Integer pageNum = map.get("pageNum");
        Integer pageSize = map.get("pageSize");

        logger.info("userCookiesName:" + userCookiesName);
        RedisKey redisKey = new RedisKey(userCookiesName, "");
        try {
            AppUserCacheInfo appUserCacheInfo = (AppUserCacheInfo) redisTemplate.getObjectFromC(redisKey, AppUserCacheInfo.class);
            if (appUserCacheInfo != null)
                return userDynamicService.getFirstNewsList(pageNum, pageSize, appUserCacheInfo.getUser_id());
            else
                return userDynamicService.getFirstNewsList(pageNum, pageSize, null);
        } catch (Exception e) {
            logger.error("获取精选动态列表失败；{}", e);
            return APIResponse.returnFail("获取精选动态列表失败");
        }
    }


    //获取达人话题列表
    @RequestMapping(value = "/getForwardTopicList", method = RequestMethod.POST, produces = "application/json")
    public APIResponse getForwardTopicList(@RequestBody ReqCommentQuery reqCommentQuery, HttpServletRequest request) {
        try {
            return topicService.getForwardTopicList(reqCommentQuery);
        } catch (Exception e) {
            logger.error("获取达人话题列表；{}", e);
            return APIResponse.returnFail("系统异常");
        }

    }


    //获取首页动态圈动态发布人
    @RequestMapping(value = "/getFirstPageMans", method = RequestMethod.POST, produces = "application/json")
    public APIResponse getFirstPageMans(@RequestBody Map map, HttpServletRequest request) {
        try {
            Object obj = map.get("iNum");
            Integer iNum = 3;
            if (obj != null)
                iNum = Integer.parseInt(obj.toString());
            return userDynamicService.getFirstPageMans(iNum);
        } catch (Exception e) {
            logger.error("获取首页动态圈动态发布人；{}", e);
            return APIResponse.returnFail("获取首页动态圈动态发布人");
        }
    }


    @RequestMapping(value = "/homePage", method = RequestMethod.POST)
    public APIResponse homePage(@RequestBody ReqHomePage reqHomePage, HttpServletRequest request) {
        try {
            Integer uid = this.getUidByUserCookiesName(request);
            reqHomePage.setUid(uid);
        } catch (Exception e) {
            logger.error("",e);
        }
        return userDynamicService.homePage(reqHomePage);
    }


    @RequestMapping(value = "/topicDetail", method = RequestMethod.POST)
    public APIResponse topicDetail(@RequestBody Map map, HttpServletRequest request) {
        Object obj = map.get("topicId");
        if (obj == null) {
            return APIResponse.returnFail("请传入有效参数！");
        }
        return topicService.queryTopicDetail(Integer.parseInt(obj.toString()));
    }


    @RequestMapping(value = "/index", method = RequestMethod.POST)
    public APIResponse queryHomePage(HttpServletRequest request) {
        try {
            Integer uid = this.getUidByUserCookiesName(request);
            ReqHomePage reqHomePage = new ReqHomePage();
            reqHomePage.setUid(uid);
            RespHomePage respHomePage = homePageService.queryHomePage(reqHomePage);
            return APIResponse.returnSuccess(respHomePage);
        } catch (Exception e) {
            logger.error("{}", e);
            return APIResponse.returnFail("");
        }
    }


}
